/*
 * @Author: zhangwei 1405298045@qq.com
 * @Date: 2022-02-12 17:14:19
 * @LastEditTime: 2022-04-06 10:00:45
 * @LastEditors: zhangwei 1405298045@qq.com
 * @Description:
 * @FilePath: /ll-fe-mp-dyfx/src/service/index.js
 *
 */
import Store from '@/store';
import Request from 'luch-request';
import requestConfig from '@/config';
import { clearAllLocal } from '@/utils';
import { getLocal } from '@/utils';
import srorageKey from '@/utils/srorage/key';
const http = new Request({
	baseURL: requestConfig.BASE_URL
});

// 请求拦截
http.interceptors.request.use(
	(config) => {
		const { method, header, ...otherParams } = config;
		const {
			custom: { isFrom }
		} = otherParams;

		const filterHeaders = Object.assign(
			{
				...header,
				Authorization: Store.getters['getToken']
			},
			isFrom && {
				'Content-Type': 'application/x-www-form-urlencoded'
			}
		);

		return {
			...otherParams,
			method,
			header: filterHeaders
		};
	},

	(config) => {
		return Promise.reject(config);
	}
);

// 响应拦截
http.interceptors.response.use(
	(response) => {
		const data = response?.data || {};
		/* eslint-disable */
		if (data.hasOwnProperty('code')) {
			const { code, message } = data;
			/**
			 * 无权限访问
			 */
			if (code === 401) {
				/**
				 * 清楚所有缓存
				 */
				clearAllLocal();

				return Promise.reject(data);
			}

			/**
			 * 报错 全局提示
			 */
			if (code !== 200) {
				uni.hideToast();

				uni.showToast({
					mask: true,
					icon: 'none',
					title: message,
					success: (res) => {
						/**
						 * 账号禁用
						 */
						if (code === 2020) {
							clearAllLocal(true);

							setTimeout((e) => {
								uni.navigateBack();
							}, 1000);
						}
					}
				});

				return Promise.reject(data);
			}
		}
		/* eslint-enable */

		return data;
	},

	(response) => {
		return Promise.reject(response);
	}
);
export default http;

export function GET(url, params = {}, otherParams = {}) {
	return http.get(url, {
		params,
		...otherParams
	});
}

export function POST(url, params, otherParams) {
	return http.post(url, params, otherParams);
}
